package com.debao.wechat;

import com.debao.common.annotation.Anonymous;
import com.debao.common.constant.Constants;
import com.debao.common.constant.WechatConstants;
import com.debao.common.core.controller.BaseController;
import com.debao.common.core.domain.AjaxResult;
import com.debao.common.core.domain.R;
import com.debao.common.enums.OrderTypePrefix;
import com.debao.common.utils.SecurityUtils;
import com.debao.common.utils.StringUtils;
import com.debao.common.utils.uuid.IdUtils;
import com.debao.common.utils.wechat.PayUtils;
import com.debao.dto.*;
import com.debao.system.domain.*;
import com.debao.system.service.*;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 微信支付接口
 */

@RestController
@RequestMapping("/api/refund")
@Slf4j
public class ApiRefund extends BaseController {


    /**
     * 场馆预约订单退款
     */
    @PostMapping("/postStadiumTableOrderRefund")
    public R<Object> postStadiumTableOrderRefund(@RequestBody @Valid StadiumTablePayRefundDto dto) throws Exception {
        log.info("postStadiumTableOrderRefund dto:{}", dto);
        // 调用支付
        String xml = PayUtils.paramsRefundFormat(dto.getTransactionId(),dto.getRefundAmount(),dto.getRemark());
        if (xml.isEmpty()) {
            return R.fail("退款参数错误");
        }
        Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
        if (!resultMap.get("return_code").equals("SUCCESS")){
            return R.fail("退款失败:" + resultMap.get("return_msg"));
        }
        if (!resultMap.get("result_code").equals("SUCCESS")) {
            return R.fail("退款失败：" + resultMap.get("err_code_des"));
        }
        return R.ok("退款成功,请等待微信回调");
    }

    /**
     * 微信退款成功回调
     */
    @PostMapping("/callback")
    @Anonymous
    public void callBack(HttpServletRequest request) throws Exception {
        Map<String, String> map = PayUtils.parseXml(request.getInputStream());
        log.info("微信退款成功回调 map = {} ", map);
        // todo: 处理退款成功逻辑
    }

}
